import { useUserStore } from '@/stores/user'
import Request from 'luch-request'

const request = new Request({
  baseURL: 'https://consult-api.itheima.net',
  custom:{
    loading: true
  }
})

// 白名单
const whiteList  = ['/login','/code','/login/password']

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 统一添加token
    const store = useUserStore()
    if(store.token && !whiteList.includes(config.url as string)){
      config.header!.Authorization = `Bearer ${store.token}`
    }
    if(config.custom?.loading){
      uni.showLoading({title:"请求中..."})
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 配置响应拦截器
request.interceptors.response.use(
  (res) => {
    uni.hideLoading()
    // 统一错误处理
    if (res.data.code !== 10000) {
      uni.showToast({
        title: '请求失败！',
        icon: 'none'
      })
      return Promise.reject(res.data)
    }

    return res.data.data
  },
  (error) => {
    uni.hideLoading()
    if (error.data.code === 401) {
      // 清除token
      const store = useUserStore()
      uni.showToast({
        title: '登陆超时，请重新登陆！',
        icon: 'none'
      })
       store.removeToken()
       // 跳转登录页
       uni.redirectTo({
         url: '/pages/login/login',
       })
    }
    return Promise.reject(error)
  }
)

export default request